package leetcode

//todo
//需要会员
/**
 * Given a binary sort.getArray, find the maximum number of consecutive 1s in this sort.getArray if you can flip at most one 0.

Example 1:

Input: [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
After flipping, the maximum number of consecutive 1s is 4.


Note:

The input sort.getArray will only contain 0 and 1.
The length of input sort.getArray is a positive integer and will not exceed 10,000


Follow up:
What if the input numbers come in one by one as an infinite stream? In other words,
you can't store all numbers coming from the stream as it's too large to hold in memory.
Could you solve it efficiently?

 similar [findMaxConsecutiveOnesIII]
 */

fun main(args: Array<String>) {
    println(findMaxConsecutiveOnesII(intArrayOf(1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0)))
}

//Classic 连续计数

//有一次翻转0->1的机会
fun findMaxConsecutiveOnesII(nums: IntArray): Int {

    var max = 0
    var counter = 0
    var prevCounter = 0
    var i = 0
    while (i < nums.size) {  //每次进来计数+1
        counter++
        //如果是0，重置，并且保存当前连续1的最大次数
        if (nums[i] == 0) {
            prevCounter = counter
            counter = 0
        }

        max = Math.max(max, prevCounter + counter)
        i++
    }
    return max
}


